﻿using AutoMapper;
using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Application.Base;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Services.AdminUser.Repository.Repositorys;
using Dora.Services.Product.Dto.QueryDto;
using Dora.Services.Supplier.Dto.ViewDto;
using Dora.Tools.Enums.AdminUser;
using Dora.Tools.Utility.Const;
using Dora.Tools.Utility.Models;
using Mapster;
using Microsoft.Extensions.Logging;
using SqlSugar;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Application
{
    /// <summary>
    /// 组织机构微服务
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class OrganizationService : DoraServiceBase, IOrganizationService
    {
        private ISugarUnitOfWork _unitOfWork;
        private readonly OrganizationRepository _repository;
        private readonly RoleRepository _roleRepository;

        public OrganizationService(ISugarUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _repository = new OrganizationRepository(unitOfWork);
        }

        /// <summary>
        /// 保存组织机构信息
        /// </summary>
        /// <param name="organization"></param>
        /// <returns></returns>
        public async Task<int> SaveOrganizationInfo(OrganizationEditDto organization)
        {
            var organizationEntity = organization.Adapt<OrganizationEntity>();
            var parentOrg = await _repository.GetOrganizationInfoById(organization.ParentId);
            if (organization.Id <= 0)
            {
                organizationEntity.RootId = (parentOrg == null) ? 0 : (parentOrg.LevelPath.Split(',').Select(int.Parse).FirstOrDefault());
                //如果新创建分社，那么把大社已签约的供应商数量同步给分社
                if (organizationEntity.OrgLevel == (int)OrgLevel.Branch) organizationEntity.SupplierCount = (parentOrg == null) ? 0 : (parentOrg.SupplierCount);
                //如果创建分社或者门店，则把大社已设置的是否需要纸质合同同步给自己
                if (organizationEntity.OrgLevel == (int)OrgLevel.Branch || organizationEntity.OrgLevel == (int)OrgLevel.Store || organizationEntity.OrgLevel == (int)OrgLevel.DirectlyUnder)
                {
                    var rootOrg = await _repository.GetOrganizationInfoById(organizationEntity.RootId);
                    organizationEntity.IsNeedPaperContract = rootOrg.IsNeedPaperContract;
                }
                //如果是大社，肯定可以更换保险,门店肯定不可以
                if (organizationEntity.OrgLevel == (int)OrgLevel.Master) organizationEntity.IsContractInsuranceSupplier = (int)AllowContractInsuranceSupplier.Yes;
                if (organizationEntity.OrgLevel == (int)OrgLevel.Store || organizationEntity.OrgLevel == (int)OrgLevel.DirectlyUnder) organizationEntity.IsContractInsuranceSupplier = (int)AllowContractInsuranceSupplier.No;

                //分社及其下级机构（包含分社的直属门店和门店）对于总社来说都属于分销商
                if (parentOrg != null && parentOrg.OrgLevel == (int)OrgLevel.Branch)
                    organizationEntity.OrgType = (int)OrgType.Distributor;

                organizationEntity.CreatedUserId = organization.UserId;
                organizationEntity.CreatedUserName = organization.UserName;
                organizationEntity.CreatedTime = DateTime.Now;
            }
            else
            {
                organizationEntity.UpdatedUserId = organization.UserId;
                organizationEntity.UpdatedUserName = organization.UserName;
                organizationEntity.UpdatedTime = DateTime.Now;
            }

            var modifyClient = _unitOfWork.ModifyClient;
            try
            {
                bool isInsert = organizationEntity.Id == 0;

                modifyClient.Ado.BeginTran();
                var orgId = _repository.SaveOrganizationInfo(organizationEntity, modifyClient);

                //计算组织机构层级/路径，并更新层级/路径字段
                if (organizationEntity.ParentId <= 0)
                {
                    organizationEntity.Id = orgId;
                    organizationEntity.LevelIdx = 0;
                    organizationEntity.LevelPath = $"{orgId},";
                }
                else
                {
                    organizationEntity.Id = orgId;
                    organizationEntity.LevelIdx = parentOrg.LevelIdx + 1;
                    organizationEntity.LevelPath = $"{parentOrg.LevelPath}{orgId},";
                    //更新是否有子级机构
                    parentOrg.HasSub = 1;
                    modifyClient.Updateable(parentOrg).UpdateColumns(it => new { it.HasSub }).Where(x => x.Id == parentOrg.Id).ExecuteCommandHasChange();
                }

                var result = modifyClient.Updateable(organizationEntity).UpdateColumns(it => new { it.HasSub, it.LevelIdx, it.LevelPath }).Where(x => x.Id == orgId).ExecuteCommandHasChange();

                modifyClient.Ado.CommitTran();

                return orgId;
            }
            catch (Exception ex)
            {
                modifyClient.Ado.RollbackTran();
                Console.WriteLine(ex);
                throw ex;
            }

        }

        /// <summary>
        /// 删除组织机构信息
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteOrganization(int orgId)
        {
            var result = await _repository.DeleteOrganization(orgId);
            return result;
        }

        /// <summary>
        /// 根据主键查询组织机构信息（编辑页面）
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<OrganizationEditDto> GetOrganizationInfoById(int orgId)
        {
            var orgEntityInfo = await _repository.GetOrganizationInfoById(orgId);
            if (orgEntityInfo == null)
                throw new ArgumentNullException($"找不到id为{orgId}的组织机构信息");

            var orgInfo = orgEntityInfo.Adapt<OrganizationEditDto>();

            //查询上级机构名称
            if (orgInfo != null)
            {
                var levelPathList = await GetOrgLevelInfoList(orgInfo.LevelPath);
                if (levelPathList != null && levelPathList.Any())
                {
                    orgInfo.OrgIds = orgInfo.LevelPath;
                    orgInfo.OrgNames = string.Join("/", levelPathList.Select(x => x.ShortName));
                }

                var parentOrgInfo = await _repository.GetOrganizationInfoById(orgEntityInfo.ParentId);
                if (parentOrgInfo == null || orgInfo.ParentId <= 0)
                {
                    orgInfo.ParentOrgName = "--";
                    orgInfo.ParentOrgLevel = -1;
                }
                else
                {
                    orgInfo.ParentOrgName = parentOrgInfo.Name;
                    orgInfo.ParentOrgLevel = parentOrgInfo.OrgLevel;
                }
            }
            return orgInfo;
        }

        /// <summary>
        /// 查询指定LevelPath中的Id所对应的机构列表
        /// </summary>
        /// <param name="orgLevelPath"></param>
        /// <returns></returns>
        public async Task<List<OrganizationDto>> GetOrgLevelInfoList(string orgLevelPath)
        {
            var orgEntityList = await _unitOfWork.QueryClient.SqlQueryable<OrganizationEntity>($"select id,Name,ShortName,OrgLevel,ParentId,CreditCode,Address,LevelPath,LeaderName,LeaderPhone from organization where id in ({orgLevelPath.TrimEnd(',')}) and isDeleted=0").ToListAsync();
            if (orgEntityList == null) return null;

            var orgList = orgEntityList.Adapt<List<OrganizationDto>>();
            return orgList;
        }

        /// <summary>
        /// 根据主键查询组织机构信息
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<OrganizationDto> GetOrgInfoById(int orgId)
        {
            var orgEntityInfo = await _repository.GetOrganizationInfoById(orgId);
            if (orgEntityInfo == null)
                throw new ArgumentNullException($"找不到id为{orgId}的组织机构信息");

            var orgInfo = orgEntityInfo.Adapt<OrganizationDto>();
            return orgInfo;
        }

        /// <summary>
        /// 根据主键查询组织机构实体信息
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<OrganizationEntity> GetById(int id)
        {
            var orgEntityInfo = await _repository.GetOrganizationInfoById(id);
            return orgEntityInfo;
        }

        /// <summary>
        /// 查询指定机构Id及下属机构集合
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<List<OrganizationEntity>> GetSubOrganizations(int orgId)
        {
            var subList = await _repository.GetSubOrganizations(orgId);
            return subList;
        }

        /// <summary>
        /// 查询指定Id的组织机构的下一级机构列表
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<List<OrganizationDto>> GetSubOrgList(int orgId)
        {
            if (orgId <= 0)
                throw new ArgumentNullException("参数非法：orgId只能大于0!");
            var subEntityList = await _repository.GetSubOrgList(orgId);

            try
            {
                var subList = subEntityList.Adapt<List<OrganizationDto>>();
                return subList;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 查询指定Id的组织机构的门店列表
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<List<OrganizationDto>> GetStoreOrgList(int orgId)
        {
            if (orgId <= 0) throw new ArgumentNullException("参数非法：orgId只能大于0!");
            //var subEntityList = await _repository.GetOrgList(orgId, OrgLevel.Store);
            var db = _unitOfWork.QueryClient;
            var orgInfo = await _repository.GetOrganizationInfoById(orgId);

            if (orgInfo == null) throw new InvalidOperationException($"找不到{orgId}的组织机构信息！");

            var subEntityList = await db.Queryable<OrganizationEntity>()
                .Where(x => x.LevelPath.StartsWith(orgInfo.LevelPath) && x.IsDeleted == 0
                        && (x.OrgLevel == (int)OrgLevel.Store || x.OrgLevel == (int)OrgLevel.DirectlyUnder)
                        ).ToListAsync();
            try
            {
                var subList = subEntityList.Adapt<List<OrganizationDto>>();
                if (subList == null) return null;

                foreach (var item in subList)
                {
                    if (item.ParentId <= 0)
                    {
                        item.ParentOrgName = "--";
                        item.ParentOrgLevel = -1;
                    }
                    else
                    {
                        var parentOrgInfo = await _repository.GetOrganizationInfoById(item.ParentId);
                        item.ParentOrgName = parentOrgInfo.Name;
                        item.ParentOrgLevel = parentOrgInfo.OrgLevel;
                    }
                }

                return subList;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }

        }

        /// <summary>
        /// 分页获取数据(单层级)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationEntity>> GetPageList(OrganizationQueryDto input)
        {
            var pageList = await _repository.GetPageList(input);
            return pageList;
        }

        /// <summary>
        /// 分页获取数据（带组织机构层级）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationDto>> GetOrganizationPageList(OrganizationQueryDto input)
        {
            var dtoList = new List<OrganizationDto>();
            var pageList = await _repository.GetPageList(input);

            foreach (var orgEntity in pageList.PageData)
            {
                var children = await GetSubOrganizations(orgEntity.Id);
                var orgInfoDto = new OrganizationDto()
                {
                    Id = orgEntity.Id,
                    Name = orgEntity.Name,
                    ShortName = orgEntity.ShortName,
                    OrgLevel = orgEntity.OrgLevel,
                    CityName = orgEntity.CityName,
                    DistrictName = orgEntity.DistrictName,
                    ProvinceName = orgEntity.ProvinceName,
                    TownName = orgEntity.TownName,
                    Address = orgEntity.Address,
                    IsDisabled = orgEntity.IsDisabled,
                    IsFrozen = orgEntity.IsFrozen,
                    IsAllowOpenStores = orgEntity.IsAllowOpenStores,
                    children = GetChildren(orgEntity, children)
                };

                if (orgEntity.ParentId <= 0)
                {
                    orgInfoDto.ParentOrgName = "--";
                    orgInfoDto.ParentOrgLevel = -1;

                }
                else
                {
                    var parentOrgInfo = await _repository.GetOrganizationInfoById(orgEntity.ParentId);
                    orgInfoDto.ParentOrgName = parentOrgInfo.Name;
                    orgInfoDto.ParentOrgLevel = parentOrgInfo.OrgLevel;
                    orgInfoDto.ParentIsAllowOpenStores = parentOrgInfo.IsAllowOpenStores;
                }

                dtoList.Add(orgInfoDto);
            }

            var orgPageList = new PageDataList<OrganizationDto>(pageList.TotalCount, dtoList, pageList.PageIndex, pageList.PageSize);
            return orgPageList;
        }

        /// <summary>
        /// 查询组织机构树
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<List<OrganizationDto>> GetOrganizationTreeList(OrganizationQueryDto query)
        {
            var dtoList = new List<OrganizationDto>();
            var orgLevel = OrgLevel.Master;

            //如果传递了ParentOrgId， 则表示要查询该机构的下属机构层级关系
            if (query.ParentOrgId.HasValue && query.ParentOrgId >= 0)
            {
                var orgInfo = await GetOrgInfoById(query.ParentOrgId.Value);
                if (orgInfo != null) orgLevel = (OrgLevel)orgInfo.OrgLevel;
            }

            var parentList = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>()
                .Where(x => x.LevelIdx == (int)orgLevel && x.IsDeleted == 0)
                .WhereIF(query.ParentOrgId >= 0, x => x.Id == query.ParentOrgId)
                .WhereIF(!string.IsNullOrEmpty(query.Keywords), x => x.Name.Contains(query.Keywords)).ToListAsync();



            foreach (var orgEntity in parentList)
            {
                var children = await GetSubOrganizations(orgEntity.Id);
                var orgInfoDto = new OrganizationDto()
                {
                    Id = orgEntity.Id,
                    Name = orgEntity.Name,
                    ShortName = orgEntity.ShortName,
                    ParentId = orgEntity.ParentId,
                    OrgLevel = orgEntity.OrgLevel,
                    CityName = orgEntity.CityName,
                    DistrictName = orgEntity.DistrictName,
                    ProvinceName = orgEntity.ProvinceName,
                    TownName = orgEntity.TownName,
                    Address = orgEntity.Address,
                    children = GetChildren(orgEntity, children),
                    LevelPath = orgEntity.LevelPath,


                };

                if (orgEntity.ParentId <= 0)
                {
                    orgInfoDto.ParentOrgName = "--";
                    orgInfoDto.ParentOrgLevel = -1;

                }
                else
                {
                    var parentOrgInfo = await _repository.GetOrganizationInfoById(orgEntity.ParentId);
                    orgInfoDto.ParentOrgName = parentOrgInfo.Name;
                    orgInfoDto.ParentOrgLevel = parentOrgInfo.OrgLevel;
                }

                dtoList.Add(orgInfoDto);
            }

            return dtoList;
        }

        /// <summary>
        /// 查询指定层级的组织机构集合（单层级，不带子）
        /// </summary>
        /// <param name="orgLevelIdx">0:总社、1:分社、2:门店</param>
        /// <returns></returns>
        public async Task<List<OrganizationDto>> GetMasterOrgList()
        {
            var dtoList = new List<OrganizationDto>();
            var orgList = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Where(x => x.LevelIdx == (int)OrgLevel.Master && x.IsDeleted == 0).ToListAsync();

            foreach (var orgEntity in orgList)
            {
                var orgInfoDto = new OrganizationDto()
                {
                    Id = orgEntity.Id,
                    Name = orgEntity.Name,
                    ShortName = orgEntity.ShortName,
                    OrgLevel = orgEntity.OrgLevel,
                    CityName = orgEntity.CityName,
                    DistrictName = orgEntity.DistrictName,
                    ProvinceName = orgEntity.ProvinceName,
                    TownName = orgEntity.TownName,
                    Address = orgEntity.Address,
                    HasSub = orgEntity.HasSub,
                    HasInsuranceSub = HasSubInsuranceOrgs(orgEntity.Id),
                    ParentOrgName = "--",
                    ParentOrgLevel = -1
                };
                dtoList.Add(orgInfoDto);
            }

            return dtoList;
        }

        /// <summary>
        /// 查询指定orgId的下级有独立保险签约资质的分社列表
        /// </summary>
        /// <returns></returns>
        [Obsolete("分社能否签约保险供应商这个开关含义后期已变更为是否允许更换产品保险，故此接口含义也同步变更")]
        public async Task<List<OrganizationDto>> GetSubInsuranceOrgs(int orgId)
        {
            var dtoList = new List<OrganizationDto>();
            var orgList = await GetSubOrgListForInsurance(orgId);
            var subOrgList = orgList.Adapt<List<OrganizationDto>>();

            subOrgList.ForEach(x =>
            {
                var result = HasSubInsuranceOrgs(x.Id);
                x.HasInsuranceSub = result;
            });

            return subOrgList;
        }

        /// <summary>
        /// 设置组织机构冻结/解冻状态
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="isFrozen"></param>
        /// <returns></returns>
        public async Task<bool> SetOrgFreeze(OrgStateSetDto stateSetDto)
        {
            var result = true;

            if (stateSetDto.OrgId <= 0)
                throw new ArgumentNullException("非法的参数:组织机构Id小于或者等于零!");

            var orgInfo = await _repository.GetOrganizationInfoById(stateSetDto.OrgId);
            if (orgInfo == null)
                throw new ArgumentException($"找不到Id为{stateSetDto.OrgId}的组织机构信息");

            orgInfo.IsFrozen = stateSetDto.IsFrozen;
            orgInfo.UpdatedTime = DateTime.Now;
            orgInfo.UpdatedUserId = stateSetDto.OperateUserId;
            orgInfo.UpdatedUserName = stateSetDto.OperateUserName;
            if (stateSetDto.FreezeType == FreezeType.Single)
            {
                //单体冻结解冻
                orgInfo.FreezeType = orgInfo.IsFrozen == 1 ? (int)stateSetDto.FreezeType : 0;
                result = await _unitOfWork.ModifyClient.Updateable(orgInfo)
                    .UpdateColumns(it => new { it.IsFrozen, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName, it.FreezeType })
                    .Where(x => x.Id == stateSetDto.OrgId).ExecuteCommandHasChangeAsync();
            }
            else if (stateSetDto.FreezeType == FreezeType.All)
            {
                //冻结/解冻当前组织机构之下的所有分社/门店
                orgInfo.FreezeType = orgInfo.IsFrozen == 1 ? (int)stateSetDto.FreezeType : 0;
                result = await _unitOfWork.ModifyClient.Updateable(orgInfo)
                    .UpdateColumns(it => new { it.IsFrozen, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName, it.FreezeType })
                    .Where(x => x.LevelPath.StartsWith(orgInfo.LevelPath)).ExecuteCommandHasChangeAsync();
            }

            return result;
        }

        /// <summary>
        /// 设置组织机构禁用/启用状态
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="isFrozen"></param>
        /// <returns></returns>
        public async Task<bool> SetOrgDisabled(OrgStateSetDto stateSetDto)
        {
            var result = true;
            if (stateSetDto.OrgId <= 0)
                throw new ArgumentNullException("非法的参数:组织机构Id小于或者等于零!");

            var orgInfo = await _repository.GetOrganizationInfoById(stateSetDto.OrgId);
            if (orgInfo == null)
                throw new ArgumentException($"找不到Id为{stateSetDto.OrgId}的组织机构信息");

            orgInfo.IsDisabled = stateSetDto.IsDisabled;
            orgInfo.UpdatedTime = DateTime.Now;
            orgInfo.UpdatedUserId = stateSetDto.OperateUserId;
            orgInfo.UpdatedUserName = stateSetDto.OperateUserName;

            //禁用/启用当前组织机构之下的所有分社/门店
            result = await _unitOfWork.ModifyClient.Updateable(orgInfo).UpdateColumns(it => new { it.IsDisabled, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName }).
                Where(x => x.LevelPath.StartsWith(orgInfo.LevelPath)).ExecuteCommandHasChangeAsync();

            return result;
        }

        /// <summary>
        /// 查询用户组织机构映射信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<TasOrgUserMapEntity> GetOrgUserMapInfo(Guid userId, int orgId)
        {
            var mapEntity = await _repository.GetOrgUserMapInfo(userId, orgId);
            return mapEntity;
        }

        /// <summary>
        /// 查询组织机构的类型
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<ResultDto<PermissionOrgType>> GetPermissionOrgType(int orgId)
        {
            var orgInfo = await GetOrganizationInfoById(orgId);
            if (orgInfo == null) return ResultDto<PermissionOrgType>.Error($"找不到Id为{orgId}的组织机构信息!");

            //大社
            if (orgInfo.OrgType == (int)OrgType.General && orgInfo.OrgLevel == (int)OrgLevel.Master)
                return ResultDto<PermissionOrgType>.Success(PermissionOrgType.BigTravelAgency);
            //直属门店
            else if (orgInfo.OrgType == (int)OrgType.DirectlyUnder && orgInfo.OrgLevel == (int)OrgLevel.DirectlyUnder)
                return ResultDto<PermissionOrgType>.Success(PermissionOrgType.DirectShop);
            //分销商
            else if (orgInfo.OrgType == (int)OrgType.Distributor)
            {
                //分社
                if (orgInfo.OrgLevel == (int)OrgLevel.Branch)
                    return ResultDto<PermissionOrgType>.Success(PermissionOrgType.SubTravelAgency);
                //门店
                else if (orgInfo.OrgLevel == (int)OrgLevel.Store)
                    return ResultDto<PermissionOrgType>.Success(PermissionOrgType.Shop);
            }

            return ResultDto<PermissionOrgType>.Error("未知机构类型");
        }

        #region 设置企业/门店信息

        /// <summary>
        /// 查询大社/分社企业信息
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<TravelServiceOrgEditDto> GetTravelServiceOrgInfo(int orgId)
        {
            var orgEntityInfo = await _repository.GetOrganizationInfoById(orgId);
            if (orgEntityInfo == null)
                throw new ArgumentNullException($"找不到id为{orgId}的组织机构信息");

            var orgInfo = orgEntityInfo.Adapt<TravelServiceOrgEditDto>();
            return orgInfo;
        }

        /// <summary>
        /// 查询门店企业信息
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<StoreInfoEditDto> GetStoreOrgInfo(int orgId)
        {
            var orgEntityInfo = await _repository.GetOrganizationInfoById(orgId);
            if (orgEntityInfo == null)
                throw new ArgumentNullException($"找不到id为{orgId}的组织机构信息");

            if (orgEntityInfo.OrgLevel == (int)OrgLevel.DirectlyUnder)
            {
                var parentOrgInfo = await _repository.GetOrganizationInfoById(orgEntityInfo.ParentId);
                if (parentOrgInfo == null) Console.WriteLine($"查询门店企业信息：找不到Id为{orgId}的上级机构信息!");
                else orgEntityInfo.CreditCode = parentOrgInfo.CreditCode;
            }

            var orgInfo = orgEntityInfo.Adapt<StoreInfoEditDto>();

            //将店内照片组装为数组方便前端展示
            if (!string.IsNullOrEmpty(orgEntityInfo.InstorePhoto1) || !string.IsNullOrEmpty(orgEntityInfo.InstorePhoto2) || !string.IsNullOrEmpty(orgEntityInfo.InstorePhoto3))
            {
                orgInfo.InstorePhotoes = new List<string>();
                if (!string.IsNullOrEmpty(orgEntityInfo.InstorePhoto1)) orgInfo.InstorePhotoes.Add(orgEntityInfo.InstorePhoto1);
                if (!string.IsNullOrEmpty(orgEntityInfo.InstorePhoto2)) orgInfo.InstorePhotoes.Add(orgEntityInfo.InstorePhoto2);
                if (!string.IsNullOrEmpty(orgEntityInfo.InstorePhoto3)) orgInfo.InstorePhotoes.Add(orgEntityInfo.InstorePhoto3);
            }

            return orgInfo;
        }

        /// <summary>
        /// 保存大社/分社的企业信息
        /// </summary>
        /// <param name="orgInfo"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> SaveTravelServiceOrgInfo(TravelServiceOrgEditDto orgInfo)
        {
            if (orgInfo.Id <= 0)
                return ResultDto<int>.Error("非法参数:组织机构Id不能小于或者等于零!");

            var organizationEntity = orgInfo.Adapt<OrganizationEntity>();

            var result = await _unitOfWork.ModifyClient.Updateable(organizationEntity).
                UpdateColumns(it => new
                {
                    it.Name,
                    it.ShortName,
                    it.CreditCode,
                    it.LeaderPhone,
                    it.ProvinceId,
                    it.ProvinceName,
                    it.CityId,
                    it.CityName,
                    it.DistrictId,
                    it.DistrictName,
                    it.TownId,
                    it.TownName,
                    it.Address,
                    it.OrgLicenseKeyUrl,
                    it.OrgLogoUrl,
                    it.OrgProfile,
                    it.UpdatedUserId,
                    it.UpdatedUserName,
                    it.UpdatedTime
                }).Where(x => x.Id == orgInfo.Id).ExecuteCommandHasChangeAsync();

            return ResultDto<int>.Success(organizationEntity.Id);
        }

        /// <summary>
        /// 保存门店的企业信息
        /// </summary>
        /// <param name="orgInfo"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> SaveStoreOrgInfo(StoreInfoEditDto orgInfo)
        {
            if (orgInfo.Id <= 0)
                return ResultDto<int>.Error("非法参数:组织机构Id不能小于或者等于零!");

            var organizationEntity = orgInfo.Adapt<OrganizationEntity>();

            //将前端上传的店内照片数组分解成三个字段进行数据库存储
            if (orgInfo != null && orgInfo.InstorePhotoes.Any())
            {
                for (int i = 0; i < orgInfo.InstorePhotoes.Count; i++)
                {
                    if (i == 0) organizationEntity.InstorePhoto1 = orgInfo.InstorePhotoes[i];
                    if (i == 1) organizationEntity.InstorePhoto2 = orgInfo.InstorePhotoes[i];
                    if (i == 2) organizationEntity.InstorePhoto3 = orgInfo.InstorePhotoes[i];
                }
            }

            var result = await _unitOfWork.ModifyClient.Updateable(organizationEntity).
                UpdateColumns(it => new
                {
                    it.WarningEdgeValue,
                    it.IsNeedVerify,
                    it.VerifyEdgeValue,
                    it.OrgLicenseKeyUrl,
                    it.StorePhoto,
                    it.OrgProfile,
                    it.InstorePhoto1,
                    it.InstorePhoto2,
                    it.InstorePhoto3,
                    it.UpdatedUserId,
                    it.UpdatedUserName,
                    it.UpdatedTime
                }).Where(x => x.Id == orgInfo.Id).ExecuteCommandHasChangeAsync();

            return ResultDto<int>.Success(organizationEntity.Id);
        }

        #endregion

        /// <summary>
        /// 查询给定机构下匹配关键字的下级机构列表
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="keywords"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<OrganizationDto>>> GetSubOrgListByOrgIdAndKeywords(int orgId, string keywords)
        {
            if (orgId <= 0)
                return ResultDto<List<OrganizationDto>>.Error("非法的参数:orgId小于或等于零!");

            var subOrgEntityList = await _repository.GetSubOrganizations(orgId, keywords);
            var subOrgList = subOrgEntityList.Adapt<List<OrganizationDto>>();
            return ResultDto<List<OrganizationDto>>.Success(subOrgList);
        }

        /// <summary>
        /// 更新大社/分社签约的供应商数量
        /// </summary>
        /// <param name="orgId">组织机构ID</param>
        /// <param name="supplierCount">已签约的供应商数量</param>
        /// <returns></returns>
        public async Task<ResultDto<bool>> SetSupplierCount(int orgId, int supplierCount)
        {
            if (orgId <= 0)
                return ResultDto<bool>.Error("非法的参数:orgId小于或等于零!");

            var result = await _unitOfWork.ModifyClient.Updateable<OrganizationEntity>().SetColumns(it => new OrganizationEntity() { Id = orgId, SupplierCount = supplierCount }).UpdateColumns(it => new { it.Id, it.SupplierCount }).Where(x => x.Id == orgId).ExecuteCommandHasChangeAsync();
            return ResultDto<bool>.Success(result);
        }

        /// <summary>
        /// 查询可用于和供应商进行签约的大社和具有独立签约供应商资质的分社的集合
        /// </summary>
        /// <param name="queryInfo">分页信息以及被排除的机构Id集合</param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationDto>> GetOrgListForSign(SignOrgQueryDto queryInfo)
        {
            #region 旧代码OR破坏索引影响性能屏蔽，改用Union All实现

            //var orgEntitySearchPredict = _unitOfWork.QueryClient.Queryable<OrganizationEntity>()
            //    .WhereIF(queryInfo.ExceptedOrgIds != null && queryInfo.ExceptedOrgIds.Any(),//已经存在的签约集合
            //    x => (x.OrgLevel == (int)OrgLevel.Master && !queryInfo.ExceptedOrgIds.Contains(x.Id)) ||//未签约大社
            //    (x.OrgLevel == (int)OrgLevel.Branch && x.IsAllowContractSupplier == (int)AllowContractSupplier.Yes
            //     && !queryInfo.ExceptedOrgIds.Contains(x.Id) &&!queryInfo.ExceptedOrgIds.Contains(x.ParentId)//未签约分社，并且总社也没有签约
            //     ))
            //    .WhereIF(queryInfo.ExceptedOrgIds == null || !queryInfo.ExceptedOrgIds.Any(),//不存在签约集合，则取具有可以独立签约供应商的分社
            //    (x => x.OrgLevel == (int)OrgLevel.Master //大社
            //    || (x.OrgLevel == (int)OrgLevel.Branch && x.IsAllowContractSupplier == (int)AllowContractSupplier.Yes)
            //    ))
            //    .WhereIF(!string.IsNullOrEmpty(queryInfo.OrgName),x=>x.Name.Contains(queryInfo.OrgName));

            #endregion

            //大社
            var master = _unitOfWork.QueryClient.Queryable<OrganizationEntity>()
                 .WhereIF(queryInfo.ExceptedOrgIds != null && queryInfo.ExceptedOrgIds.Any(),
                          x => x.OrgLevel == (int)OrgLevel.Master && !queryInfo.ExceptedOrgIds.Contains(x.Id))//已经存在的签约集合，则取没有签约大社
                 .WhereIF(queryInfo.ExceptedOrgIds == null || !queryInfo.ExceptedOrgIds.Any(),
                          x => x.OrgLevel == (int)OrgLevel.Master)//不存在签约集合，则取所有大社
                .WhereIF(!string.IsNullOrEmpty(queryInfo.OrgName), x => x.Name.Contains(queryInfo.OrgName));

            //分社
            var branch = _unitOfWork.QueryClient.Queryable<OrganizationEntity>()
                .WhereIF(queryInfo.ExceptedOrgIds != null && queryInfo.ExceptedOrgIds.Any(),
                            x => x.OrgLevel == (int)OrgLevel.Branch && x.IsAllowContractSupplier == (int)AllowContractSupplier.Yes
                 && !queryInfo.ExceptedOrgIds.Contains(x.Id) && !queryInfo.ExceptedOrgIds.Contains(x.ParentId))//存在签约集合，则取未签约分社，并且总社也没有签约
                .WhereIF(queryInfo.ExceptedOrgIds == null || !queryInfo.ExceptedOrgIds.Any(),//不存在签约集合，则取具有可以独立签约供应商的分社
                            x => x.OrgLevel == (int)OrgLevel.Branch && x.IsAllowContractSupplier == (int)AllowContractSupplier.Yes)
                .WhereIF(!string.IsNullOrEmpty(queryInfo.OrgName), x => x.Name.Contains(queryInfo.OrgName));

            var orgEntitySearchPredict = _unitOfWork.QueryClient.UnionAll<OrganizationEntity>(new List<ISugarQueryable<OrganizationEntity>>() { master, branch }).OrderBy(o => o.Sort).OrderBy(o => o.Id);
            var totalCount = await orgEntitySearchPredict.CountAsync();
            var orgEntityList = await orgEntitySearchPredict.ToPageListAsync(queryInfo.PageIndex, queryInfo.PageSize);
            if (orgEntityList == null) return new PageDataList<OrganizationDto>(totalCount, new List<OrganizationDto>(), queryInfo.PageIndex, queryInfo.PageSize);
            var orgList = orgEntityList.Adapt<List<OrganizationDto>>();
            var pagedOrgList = new PageDataList<OrganizationDto>(totalCount, orgList, queryInfo.PageIndex, queryInfo.PageSize);
            return pagedOrgList;
        }

        /// <summary>
        /// 查询我自己所在的机构的全部机构列表
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<OrgSimpleDto>>> GetMyTeamOrgList(int orgId)
        {
            if (orgId <= 0)
                return ResultDto<List<OrgSimpleDto>>.Error("参数非法:orgId不能小于或者等于零!");
            var orgInfo = await GetOrgInfoById(orgId);
            var rootOrgId = orgInfo.LevelPath.Split(',').FirstOrDefault();

            var orgList = await _repository.GetSubSimpleOrgList($"{rootOrgId},");
            return ResultDto<List<OrgSimpleDto>>.Success(orgList);
        }


        /// <summary>
        /// 查询距离位置附近的门店信息列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PageDataList<NearestStoreOrgDto>> GetNearestStoreOrgPageList(NearestStoreQueryDto query)
        {
            try
            {
                _ = WriteOperationLog(OperationType.Debugger, query, Guid.Empty, "", "OrganizationService GetNearestStoreOrgPageList 1");
                Console.WriteLine($"OrganizationService GetNearestStoreOrgPageList 1");

                if (query.TopOrgId <= 0)
                    throw new ArgumentException("参数非法：大社TopOrgId不能小于等于零!");
                if (query.DistRange <= 0)
                    return new PageDataList<NearestStoreOrgDto>();

                //未定位的查所有的门店
                if (query.Lat == 0M || query.Lng == 0M)
                {
                    var searchPredict = _unitOfWork.ModifyClient.Queryable<OrganizationEntity>().Where(x => x.RootId == query.TopOrgId && (x.OrgLevel == (int)OrgLevel.Store || x.OrgLevel == (int)OrgLevel.DirectlyUnder) && x.IsDeleted == 0).OrderBy(x => x.Id)
                        .Select(x => new NearestStoreOrgDto() { Id = x.Id, Name = x.Name, ShortName = x.ShortName, OrgLevel = x.OrgLevel, LeaderPhone = x.LeaderPhone, Address = x.Address.Replace("|", " "), StorePhoto = x.StorePhoto, LevelPath = x.LevelPath });
                    var totalCount = await searchPredict.CountAsync();
                    var items = await searchPredict.ToPageListAsync(query.PageIndex, query.PageSize);
                    var pagedData = new PageDataList<NearestStoreOrgDto>(totalCount, items, query.PageIndex, query.PageSize);
                    return pagedData;
                }
                else
                {
                    var nearestStores = await _repository.GetNearestStoreOrgPageList(query);
                    return nearestStores;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"OrganizationService GetNearestStoreOrgPageList msg:{ex.Message}|||st:{ex.StackTrace}");
                _ = WriteOperationLog(OperationType.Error, new { query = query, msg = ex.Message, st = ex.StackTrace }, Guid.Empty, "", "OrganizationService GetNearestStoreOrgPageList");
                return new PageDataList<NearestStoreOrgDto>();
            }
        }

        /// <summary>
        /// 根据查询条件查询组织机构列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<List<OrgSimpleDto>> GetOrgList(OrganizationQueryDto query)
        {
            var orgEntityList = await _repository.GetOrgEntityList(query);
            if (orgEntityList == null) return new List<OrgSimpleDto>();

            var orgList = orgEntityList.Adapt<List<OrgSimpleDto>>();

            return orgList;
        }

        /// <summary>
        /// 根据条件查询组织机构Id
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<List<OrganizationEntity>> GetOrgEntityList(OrganizationQueryDto query)
        {
            var orgList = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Where(x => x.IsDeleted == 0)
                .WhereIF(query.ParentOrgId > 0, x => x.ParentId == query.ParentOrgId)
                .WhereIF(!string.IsNullOrEmpty(query.Keywords), x => x.Name.Contains(query.Keywords) || x.ShortName.Contains(query.Keywords))
                .WhereIF(!string.IsNullOrEmpty(query.Leader), x => x.LeaderName.Contains(query.Leader))
                .WhereIF(!string.IsNullOrEmpty(query.Mobile), x => x.LeaderPhone.Contains(query.Mobile))
                .WhereIF(query.OrgLevel > 0, x => x.OrgLevel == query.OrgLevel)
                .WhereIF(query.ProvinceId > 0, x => x.ProvinceId == query.ProvinceId)
                .WhereIF(query.CityId > 0, x => x.CityId == query.CityId)
                .WhereIF(query.DistrictId > 0, x => x.DistrictId == query.DistrictId)
                .ToListAsync();
            return orgList;
        }

        /// <summary>
        /// 查询门店/直属门店/直属部门的信息以及与其结算的上级机构信息
        /// </summary>
        /// <param name="storeOrgId">门店/直属门店/直属部门的机构ID</param>
        /// <returns></returns>
        public async Task<ResultDto<OrgSettlementInfoDto>> GetSettlementOrgInfo(int storeOrgId)
        {
            if (storeOrgId <= 0)
                return ResultDto<OrgSettlementInfoDto>.Error("参数非法：门店storeOrgId不能小于等于零!");
            var storeOrgEditInfo = await GetOrganizationInfoById(storeOrgId);
            if (storeOrgEditInfo == null) return ResultDto<OrgSettlementInfoDto>.Error($"找不到Id为{storeOrgId}的门店信息!");
            var storeOrgInfo = new OrgSettlementInfoDto()
            {
                Id = storeOrgEditInfo.Id,
                Name = storeOrgEditInfo.Name,
                LevelPath = storeOrgEditInfo.LevelPath,
                OrgLevel = storeOrgEditInfo.OrgLevel,
                ShortName = storeOrgEditInfo.ShortName,
                RootId = storeOrgEditInfo.RootId,
                CreditCode = storeOrgEditInfo.CreditCode,
                ParentId = storeOrgEditInfo.ParentId,
                ParentOrgLevel = storeOrgEditInfo.ParentOrgLevel,
                ParentOrgName = storeOrgEditInfo.ParentOrgName
            };

            //查询上级机构性质，如果上级机构是大社或者有独立结算资质的分社，那么当前上级机构就是结算机构，直接返回
            var parentOrgInfo = await GetOrganizationInfoById(storeOrgEditInfo.ParentId);
            if (storeOrgEditInfo.ParentOrgLevel == (int)OrgLevel.Master)
            {
                storeOrgInfo.SettlementOrgInfo = new OrgSimpleDto()
                {
                    Id = parentOrgInfo.Id,
                    Name = parentOrgInfo.Name,
                    ShortName = parentOrgInfo.ShortName,
                    LevelPath = parentOrgInfo.LevelPath,
                    OrgLevel = parentOrgInfo.OrgLevel,
                    CityName = parentOrgInfo.CityName
                };
                return ResultDto<OrgSettlementInfoDto>.Success(storeOrgInfo);
            }
            //如果上级机构是分社，并且该分社没有独立签约供应商资质，也没有独立结算资质，那么结算机构就是总社
            else if ((parentOrgInfo.OrgLevel == (int)OrgLevel.Branch))
            {
                if (parentOrgInfo.IsAllowContractSupplier == (int)AllowContractSupplier.Yes)
                {
                    storeOrgInfo.SettlementOrgInfo = new OrgSimpleDto()
                    {
                        Id = parentOrgInfo.Id,
                        Name = parentOrgInfo.Name,
                        ShortName = parentOrgInfo.ShortName,
                        LevelPath = parentOrgInfo.LevelPath,
                        OrgLevel = parentOrgInfo.OrgLevel,
                        CityName = parentOrgInfo.CityName
                    };
                    return ResultDto<OrgSettlementInfoDto>.Success(storeOrgInfo);
                }
                else
                {
                    var masterOrgInfo = await GetOrganizationInfoById(parentOrgInfo.ParentId);
                    storeOrgInfo.SettlementOrgInfo = new OrgSimpleDto()
                    {
                        Id = masterOrgInfo.Id,
                        Name = masterOrgInfo.Name,
                        ShortName = masterOrgInfo.ShortName,
                        LevelPath = masterOrgInfo.LevelPath,
                        OrgLevel = masterOrgInfo.OrgLevel,
                        CityName = masterOrgInfo.CityName
                    };
                    return ResultDto<OrgSettlementInfoDto>.Success(storeOrgInfo);
                }
            }
            else
                return ResultDto<OrgSettlementInfoDto>.Error("门店机构数据异常: 门店上级机构既不是大社也不是分社!");

        }


        /// <summary>
        /// 查询门店/直属门店/直属部门的上级可开票的机构信息
        /// </summary>
        /// <param name="storeOrgId">门店/直属门店/直属部门的机构ID</param>
        /// <returns></returns>
        public async Task<ResultDto<OrgSettlementInfoDto>> GetBillingOrgInfo(int storeOrgId)
        {
            if (storeOrgId <= 0)
                return ResultDto<OrgSettlementInfoDto>.Error("参数非法：门店storeOrgId不能小于等于零!");
            var storeOrgEditInfo = await GetOrganizationInfoById(storeOrgId);
            if (storeOrgEditInfo == null) return ResultDto<OrgSettlementInfoDto>.Error($"找不到Id为{storeOrgId}的门店信息!");
            var storeOrgInfo = new OrgSettlementInfoDto()
            {
                Id = storeOrgEditInfo.Id,
                Name = storeOrgEditInfo.Name,
                OrgLevel = storeOrgEditInfo.OrgLevel,
                ShortName = storeOrgEditInfo.ShortName,
                RootId = storeOrgEditInfo.RootId,
                CreditCode = storeOrgEditInfo.CreditCode,
                ParentId = storeOrgEditInfo.ParentId,
                ParentOrgLevel = storeOrgEditInfo.ParentOrgLevel,
                ParentOrgName = storeOrgEditInfo.ParentOrgName
            };

            //查询上级机构性质，如果上级机构是大社或者有独立纳税资质的分社，那么当前上级机构就是开票机构，直接返回
            var parentOrgInfo = await GetOrganizationInfoById(storeOrgEditInfo.ParentId);
            if (storeOrgEditInfo.ParentOrgLevel == (int)OrgLevel.Master)
            {
                storeOrgInfo.SettlementOrgInfo = new OrgSimpleDto()
                {
                    Id = parentOrgInfo.Id,
                    Name = parentOrgInfo.Name,
                    ShortName = parentOrgInfo.ShortName,
                    LevelPath = parentOrgInfo.LevelPath,
                    OrgLevel = parentOrgInfo.OrgLevel,
                    CityName = parentOrgInfo.CityName
                };
                return ResultDto<OrgSettlementInfoDto>.Success(storeOrgInfo);
            }
            //如果上级机构是分社，并且该分社没有独立纳税资质，那么开票机构就是总社
            else if (parentOrgInfo.OrgLevel == (int)OrgLevel.Branch)
            {
                if (parentOrgInfo.TaxPaymentType == (int)OrgTaxPaymentType.IndependentTax)
                {
                    storeOrgInfo.SettlementOrgInfo = new OrgSimpleDto()
                    {
                        Id = parentOrgInfo.Id,
                        Name = parentOrgInfo.Name,
                        ShortName = parentOrgInfo.ShortName,
                        LevelPath = parentOrgInfo.LevelPath,
                        OrgLevel = parentOrgInfo.OrgLevel,
                        CityName = parentOrgInfo.CityName
                    };
                    return ResultDto<OrgSettlementInfoDto>.Success(storeOrgInfo);
                }
                else
                {
                    var masterOrgInfo = await GetOrganizationInfoById(parentOrgInfo.ParentId);
                    storeOrgInfo.SettlementOrgInfo = new OrgSimpleDto()
                    {
                        Id = masterOrgInfo.Id,
                        Name = masterOrgInfo.Name,
                        ShortName = masterOrgInfo.ShortName,
                        LevelPath = masterOrgInfo.LevelPath,
                        OrgLevel = masterOrgInfo.OrgLevel,
                        CityName = masterOrgInfo.CityName
                    };
                    return ResultDto<OrgSettlementInfoDto>.Success(storeOrgInfo);
                }
            }
            else
                return ResultDto<OrgSettlementInfoDto>.Error("门店机构数据异常: 门店上级机构既不是大社也不是分社!");

        }

        /// <summary>
        /// 查询指定层级、省、市、区的下属机构集合(带分页)
        /// </summary>
        /// <param name="queryInfo"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationDto>> GetChildrenOrgList(OrganizationQueryDto queryInfo)
        {
            if (queryInfo.ParentOrgId <= 0)
                throw new ArgumentNullException($"参数非法：父级组织机构是必选条件，不允许小于或者等于零!");

            var orgInfo = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().FirstAsync(x => x.Id == queryInfo.ParentOrgId && x.IsDeleted == 0);
            if (orgInfo == null)
                throw new ArgumentNullException($"找不到Id为{queryInfo.ParentOrgId}的组织机构信息");

            var searchPredict = _unitOfWork.QueryClient.Queryable<OrganizationEntity>().
                Where(x => x.LevelPath.StartsWith(orgInfo.LevelPath) && x.LevelPath != orgInfo.LevelPath)
                .WhereIF(!string.IsNullOrWhiteSpace(queryInfo.Keywords), x => x.Name.Contains(queryInfo.Keywords))
                .WhereIF(queryInfo.OrgLevel >= 0, x => x.OrgLevel == queryInfo.OrgLevel)
                .WhereIF(queryInfo.CityId > 0, x => x.CityId == queryInfo.CityId)
                .WhereIF(queryInfo.ProvinceId > 0, x => x.ProvinceId == queryInfo.ProvinceId)
                .WhereIF(queryInfo.DistrictId > 0, x => x.DistrictId == queryInfo.DistrictId)
                .OrderBy(x => x.OrgLevel).OrderBy(x => x.Id);

            var totalCount = await searchPredict.CountAsync();
            var items = await searchPredict.ToPageListAsync(queryInfo.PageIndex, queryInfo.PageSize);
            if (items == null) return new PageDataList<OrganizationDto>();
            var orgs = items.Adapt<List<OrganizationDto>>();
            var pagedData = new PageDataList<OrganizationDto>(totalCount, orgs, queryInfo.PageIndex, queryInfo.PageSize);

            return pagedData;
        }



        /// <summary>
        /// 递归查询子级机构
        /// </summary>
        /// <param name="parentOrg"></param>
        /// <param name="currentOrgSubList"></param>
        /// <returns></returns>
        private List<OrganizationDto> GetChildren(OrganizationEntity parentOrg, List<OrganizationEntity> currentOrgSubList)
        {
            var childrenList = new List<OrganizationDto>();
            var entityList = currentOrgSubList.FindAll(x => x.ParentId == parentOrg.Id);

            //如果不存在子级机构直接返回空集合
            if (entityList == null || !entityList.Any()) return childrenList;

            foreach (var orgEntity in entityList)
            {
                var orgInfoDto = new OrganizationDto()
                {
                    Id = orgEntity.Id,
                    Name = orgEntity.Name,
                    ShortName = orgEntity.ShortName,
                    OrgLevel = orgEntity.OrgLevel,
                    CityName = orgEntity.CityName,
                    CityId = orgEntity.CityId,
                    DistrictName = orgEntity.DistrictName,
                    ProvinceName = orgEntity.ProvinceName,
                    ProvinceId = orgEntity.ProvinceId,
                    TownName = orgEntity.TownName,
                    Address = orgEntity.Address,
                    IsDisabled = orgEntity.IsDisabled,
                    IsFrozen = orgEntity.IsFrozen,
                    IsAllowOpenStores = orgEntity.IsAllowOpenStores,
                    ParentId = parentOrg.Id,
                    ParentOrgLevel = parentOrg.OrgLevel,
                    ParentOrgName = parentOrg.Name,
                    LevelPath = orgEntity.LevelPath,
                    LeaderPhone = orgEntity.LeaderPhone,
                    LeaderName = orgEntity.LeaderName
                };

                //如果存在子级机构，遍历读取
                if (currentOrgSubList.Any(x => x.ParentId == orgEntity.Id))
                    orgInfoDto.children = GetChildren(orgEntity, currentOrgSubList);

                childrenList.Add(orgInfoDto);
            }

            return childrenList;
        }

        /// <summary>
        /// 判断是否存在可独立签约供应商的分社
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        private bool HasSubInsuranceOrgs(int orgId)
        {
            var hasSub = _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Any(x => x.ParentId == orgId && x.OrgLevel == (int)OrgLevel.Branch && x.IsContractInsuranceSupplier == (int)AllowContractInsuranceSupplier.Yes && x.IsDeleted == 0);
            return hasSub;
        }

        /// <summary>
        /// 获取可独立签约的供应商的分社
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        private async Task<List<OrganizationEntity>> GetSubOrgListForInsurance(int orgId)
        {
            var orgList = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Where(x => x.ParentId == orgId && x.OrgLevel == (int)OrgLevel.Branch && x.IsContractInsuranceSupplier == (int)AllowContractInsuranceSupplier.Yes && x.IsDeleted == 0).ToListAsync();
            return orgList;
        }

        /// <summary>
        /// 更改管理员
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<ResultDto> ChangeAdmin(int orgId, Guid userId)
        {
            var modifyClient = _unitOfWork.ModifyClient;
            try
            {
                modifyClient.Ado.BeginTran();

                //1 更改tas_org_user_map当前orgId历史数据isadmin为0
                var result = modifyClient.Updateable<TasOrgUserMapEntity>().SetColumns(it => new TasOrgUserMapEntity() { IsAdmin = 0 }).Where(it => it.OrgId == orgId).ExecuteCommand() > 0;

                //2 更改tas_org_user_map表中userId的isadmin为1，不存在则创建
                var orgUserMap = modifyClient.Queryable<TasOrgUserMapEntity>().Where(it => it.UserId == userId && it.OrgId == orgId).First();
                if (orgUserMap != null)
                {
                    modifyClient.Updateable<TasOrgUserMapEntity>().SetColumns(it => new TasOrgUserMapEntity() { IsAdmin = 1 }).Where(it => it.UserId == userId && it.OrgId == orgId).ExecuteCommand();
                }
                else
                {
                    //添加用户机构关系
                    TasOrgUserMapEntity tasOrgUserMapEntity = new TasOrgUserMapEntity()
                    {
                        UserId = userId,
                        OrgId = orgId,
                        IsAdmin = 1,
                        IsLeader = 0
                    };
                    modifyClient.Insertable(tasOrgUserMapEntity).ExecuteReturnEntity();
                }

                modifyClient.Ado.CommitTran();
                return ResultDto.Success(true);
            }
            catch (Exception ex)
            {
                modifyClient.Ado.RollbackTran();
                Console.WriteLine(ex);
                return ResultDto.Error("更换管理员失败");
            }
        }

        /// <summary>
        /// 更改负责人
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<ResultDto> ChangeLeader(int orgId, Guid userId)
        {
            var modifyClient = _unitOfWork.ModifyClient;
            try
            {
                modifyClient.Ado.BeginTran();

                //1 更改tas_org_user_map当前orgId历史数据IsLeader为0
                var result = modifyClient.Updateable<TasOrgUserMapEntity>().SetColumns(it => new TasOrgUserMapEntity() { IsLeader = 0 }).Where(it => it.OrgId == orgId).ExecuteCommand() > 0;

                //2 更改tas_org_user_map表中userId的IsLeader为1，不存在则创建
                var orgUserMap = modifyClient.Queryable<TasOrgUserMapEntity>().Where(it => it.UserId == userId && it.OrgId == orgId).First();
                if (orgUserMap != null)
                {
                    modifyClient.Updateable<TasOrgUserMapEntity>().SetColumns(it => new TasOrgUserMapEntity() { IsLeader = 1 }).Where(it => it.UserId == userId && it.OrgId == orgId).ExecuteCommand();
                }
                else
                {
                    //添加用户机构关系
                    TasOrgUserMapEntity tasOrgUserMapEntity = new TasOrgUserMapEntity()
                    {
                        UserId = userId,
                        OrgId = orgId,
                        IsAdmin = 0,
                        IsLeader = 1
                    };
                    modifyClient.Insertable(tasOrgUserMapEntity).ExecuteReturnEntity();
                }

                modifyClient.Ado.CommitTran();
                return ResultDto.Success(true);
            }
            catch (Exception ex)
            {
                modifyClient.Ado.RollbackTran();
                Console.WriteLine(ex);
                return ResultDto.Error("更改负责人");
            }
        }

        public async Task<PageDataList<TasOrgListItemDto>> GetOrgBranchPageList(OrganizationQueryDto input)
        {
            var pageList = await _repository.GetBranchOrgPageList(input);

            return pageList;
        }

        public async Task<List<OrganizationEntity>> GetSubBranchOrgList(int orgId, int orgLevel)
        {
            var orgList = await _repository.GetSubBranchOrgList(orgId, orgLevel);

            //var orgList = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>()
            //    .Where(x => x.IsDeleted == 0 && x.ParentId == orgId && x.OrgLevel == orgLevel).ToListAsync();
            return orgList;
        }

        /// <summary>
        /// 根据指定的orgid和level查询他的下级单位 
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="orgLevel"></param>
        /// <returns></returns>
        public async Task<List<OrganizationEntity>> GetMySubOrgList(int orgId, int orgLevel)
        {
            var modifyClient = _unitOfWork.QueryClient;
            var orgList = await modifyClient.Queryable<OrganizationEntity>().Where(x => x.IsDeleted == 0 && x.ParentId == orgId && x.OrgLevel == orgLevel)
                .ToListAsync();
            return orgList;
        }

        public async Task<List<OrgSimpleDto>> GetMySubOrgAll(int orgId)
        {
            var db = _unitOfWork.QueryClient;
            var parentOrg = await db.Queryable<OrganizationEntity>().FirstAsync(x => x.IsDeleted == 0 && x.Id == orgId);

            var orgList = await db.Queryable<OrganizationEntity>().
                Where(x => x.IsDeleted == 0 && x.LevelPath.StartsWith(parentOrg.LevelPath))
                .Select(x => new OrgSimpleDto
                {
                    LevelPath = x.LevelPath,
                    Id = x.Id,
                    OrgLevel = x.OrgLevel,
                    CityName = x.CityName,
                    Name = x.Name,
                    ShortName = x.ShortName
                })
                .ToListAsync();
            return orgList;
        }



        /// <summary>
        /// 设置门店审批状态 
        /// </summary>
        /// <param name="stateSetDto"></param>
        /// <returns></returns>
        public async Task<bool> SetAuditState(OrgStateSetDto stateSetDto)
        {
            var result = true;

            if (stateSetDto.OrgId <= 0)
                throw new ArgumentNullException("非法的参数:组织机构Id小于或者等于零!");

            var orgInfo = await _repository.GetOrganizationInfoById(stateSetDto.OrgId);
            if (orgInfo == null)
                throw new ArgumentException($"找不到Id为{stateSetDto.OrgId}的组织机构信息");

            orgInfo.AuditState = stateSetDto.AuditState;
            orgInfo.UpdatedTime = DateTime.Now;
            orgInfo.UpdatedUserId = stateSetDto.OperateUserId;
            orgInfo.UpdatedUserName = stateSetDto.OperateUserName;
            result = await _unitOfWork.ModifyClient.Updateable(orgInfo)
                .UpdateColumns(it => new { it.AuditState, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName })
                .Where(x => x.Id == stateSetDto.OrgId).ExecuteCommandHasChangeAsync();
            return result;
        }

        /// <summary>
        /// 发票管理使用
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationDto>> GetNotInIdsOrgInfo(InvoiceOrgQueryDto queryDto)
        {
            if (queryDto.ParentOrgId <= 0)
                throw new ArgumentNullException($"参数非法：父级组织机构是必选条件，不允许小于或者等于零!");
            var orgInfo = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().FirstAsync(x => x.Id == queryDto.ParentOrgId && x.IsDeleted == 0);
            if (orgInfo == null)
                throw new ArgumentNullException($"找不到Id为{queryDto.ParentOrgId}的组织机构信息");
            var searchPredict = _unitOfWork.QueryClient.Queryable<OrganizationEntity>().
                Where(x => x.LevelPath.StartsWith(orgInfo.LevelPath) && x.LevelPath != orgInfo.LevelPath)
                .WhereIF(!string.IsNullOrEmpty(queryDto.OrgName), x => x.Name.Contains(queryDto.OrgName))
                .WhereIF(queryDto.OrgIds.Count > 0, x => !queryDto.OrgIds.Contains(x.Id))
                .WhereIF(queryDto.OrgLevel > -1, x => x.OrgLevel == queryDto.OrgLevel)
                .WhereIF(queryDto.CityId > 0, x => x.CityId == queryDto.CityId)
                .WhereIF(queryDto.ProvinceId > 0, x => x.ProvinceId == queryDto.ProvinceId)
                .WhereIF(queryDto.DistrictId > 0, x => x.DistrictId == queryDto.DistrictId)
                .OrderBy(x => x.OrgLevel).OrderBy(x => x.Id);
            var totalCount = await searchPredict.CountAsync();
            var items = await searchPredict.ToPageListAsync(queryDto.PageIndex, queryDto.PageSize);
            if (items == null) return new PageDataList<OrganizationDto>();
            var orgs = items.Adapt<List<OrganizationDto>>();
            var pagedData = new PageDataList<OrganizationDto>(totalCount, orgs, queryDto.PageIndex, queryDto.PageSize);
            return pagedData;
        }

        /// <summary>
        /// 根据IdList查询机构列表
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<List<OrgSimpleDto>> GetListByIdList(List<int> idList)
        {
            if (idList == null || !idList.Any())
                return new List<OrgSimpleDto>();
            var orgList = await _repository.GetListByIdList(idList);
            return orgList;
        }

        /// <summary>
        /// 查询用户所属的机构列表
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<List<OrgDto>> GetBriefListByUserId(Guid userId)
        {
            var orgList = await _repository.GetBriefListByUserId(userId);
            return orgList;
        }


        /// <summary>
        /// 获取大社/分社下所有门店(过滤掉有独立签约资质分社下的门店)
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrgSimpleDto>> GetSubStoreList(OrganizationQueryDto queryInfo)
        {
            try
            {
                return await _repository.GetSubStoreListAsync(queryInfo);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取小程序订单设置归属门店列表
        /// </summary>
        /// <param name="orglevelpath"></param>
        /// <returns></returns>
        public async Task<List<OrganizationEntity>> GetWXSetupOrgList(string levelpath)
        {
            var modifyClient = _unitOfWork.ModifyClient;
            var orgList = await modifyClient.Queryable<OrganizationEntity>().Where(x => x.IsDeleted == 0 && x.OrgLevel == (int)OrgLevel.Store && x.LevelPath.StartsWith(levelpath))
                .ToListAsync();
            return orgList;
        }


        /// <summary>
        /// 根据指定的orgid和level查询他的下级单位 
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="orgLevel"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationCashViewDto>> GetMyCashpoolSubOrgPageList(OrganizationQueryDto queryInfo)
        {
            var modifyClient = _unitOfWork.QueryClient;
            queryInfo.LevelPath = queryInfo.LevelPath ?? "";
            queryInfo.Keywords = queryInfo.Keywords ?? "";
            //queryInfo.OrgLevel = (queryInfo.OrgLevel == 2 || queryInfo.OrgLevel == 3) ? queryInfo.OrgLevel : (short)2;
            queryInfo.OrgLevel = queryInfo.OrgLevel;

            var sql = $@"SELECT
	* 
FROM
	(
SELECT
	o.*,
	( CASE WHEN o1.IsAllowContractSupplier = 21 THEN 21 ELSE 20 END ) AS ParentIsAllowContractSupplier,
o1.Name as ParentName
FROM
	organization o
	LEFT JOIN organization o1 ON o.ParentId = o1.Id 
	) source ";
            //WHERE( o.OrgLevel = 2 OR o.OrgLevel = 3 ) 
            var query = modifyClient.SqlQueryable<OrganizationCashViewDto>(sql)
                //.WhereIF(queryInfo.OrgLevel == 2 || queryInfo.OrgLevel == 3, x => x.OrgLevel == queryInfo.OrgLevel)
                .WhereIF(queryInfo.OrgLevel > 0, x => x.OrgLevel == queryInfo.OrgLevel)
                .WhereIF(!string.IsNullOrWhiteSpace(queryInfo.LevelPath), x => x.LevelPath.StartsWith(queryInfo.LevelPath))
                .WhereIF(!string.IsNullOrWhiteSpace(queryInfo.Keywords), x => x.Name.Contains(queryInfo.Keywords))

                ;
            var list = await query.ToPageListAsync(queryInfo.PageIndex, queryInfo.PageSize);
            queryInfo.TotalCount = await query.CountAsync();
            var pageData = list.ToPageDataList(queryInfo);
            return pageData;
        }



        /// <summary>
        /// 根据指定的orgid和level查询他的下级单位 
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="orgLevel"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<OrganizationEntity>>> GetSettlementBySelfBrancheList(int orgId)
        {

            var db = _unitOfWork.QueryClient;
            var parentOrg = await db.Queryable<OrganizationEntity>().FirstAsync(x => x.IsDeleted == 0 && x.Id == orgId);
            if (parentOrg == null || parentOrg.OrgLevel != 0)
            {
                return ResultDto<List<OrganizationEntity>>.Error("此机构不是正确的大社");
            }
            var list = await db.Queryable<OrganizationEntity>().Where(x => x.IsDeleted == 0 && x.ParentId == orgId && x.IsAllowContractSupplier == 21).ToListAsync();
            return ResultDto<List<OrganizationEntity>>.Success(list);
        }

        /// <summary>
        /// 修改小程序企业介绍
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> UpdateOrgMPOrgProfile(OrgMPOrgProfileSaveDto input)
        {
            if (input.Id <= 0)
                return ResultDto<int>.Error("非法参数:组织机构Id不能小于或者等于零!");

            var organizationEntity = input.Adapt<OrganizationEntity>();
            organizationEntity.UpdatedTime = DateTime.Now;

            var result = await _unitOfWork.ModifyClient.Updateable(organizationEntity).
                UpdateColumns(it => new
                {
                    it.MPOrgProfile,
                    it.UpdatedUserId,
                    it.UpdatedUserName,
                    it.UpdatedTime
                }).Where(x => x.Id == input.Id).ExecuteCommandHasChangeAsync();

            return ResultDto<int>.Success(organizationEntity.Id);
        }
        /// <summary>
        /// 查询组织机构集合
        /// </summary>
        /// <param name="queryInfo"></param>
        /// <returns></returns>
        public async Task<List<OrganizationEntity>> GetOrganizationEntities(OrganizationSQueryDto queryInfo)
        {
            return await _unitOfWork.QueryClient.Queryable<OrganizationEntity>()
                .WhereIF(queryInfo.ParentOrgId.HasValue, t => t.ParentId == queryInfo.ParentOrgId)
                .WhereIF(queryInfo.OrgLevel.HasValue, t => t.OrgLevel == queryInfo.OrgLevel)
                .WhereIF(queryInfo.OrgId.HasValue, t => t.Id == queryInfo.OrgId)
                .ToListAsync();
        }

        /// <summary>
        /// 根据大社Id获取大社下的全部独立分社
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<List<int>> GetIsAllowContractSupplierBranch(int orgId)
        {
            var res = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Where(x => x.IsDeleted == 0 && x.RootId == orgId && x.OrgLevel == (int)OrgLevel.Branch && x.IsContractInsuranceSupplier == (short)AllowContractSupplier.Yes).ToListAsync();
            if (res.Count > 0)
            {
                return res.Select(x => x.Id).ToList();
            }
            return new List<int>();
        }

        /// <summary>
        /// TAS我的供应商区域设置获取组织机构信息分页列表
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationDto>> GetMySupplierOrgQueryInfo(MySupplierOrgQueryDto queryDto)        {            if (queryDto.CurrentOrgLevel == (int)OrgLevel.Branch) //分社只获取分社下门店
            {                var searchPredict = _unitOfWork.QueryClient.Queryable<OrganizationEntity>()                .Where(x => x.IsDeleted == 0 && x.LevelPath.StartsWith(queryDto.CurrentLevelPath) && x.LevelPath != queryDto.CurrentLevelPath)                .WhereIF(queryDto.OrgIds != null, x => !queryDto.OrgIds.Contains(x.Id)) //---过滤分社                .WhereIF(!string.IsNullOrEmpty(queryDto.KeyWords), x => x.Name.Contains(queryDto.KeyWords))                .WhereIF(queryDto.CityId > 0, x => x.CityId == queryDto.CityId)                .WhereIF(queryDto.ProvinceId > 0, x => x.ProvinceId == queryDto.ProvinceId)                .OrderBy(x => x.OrgLevel).OrderBy(x => x.Id);                var totalCount = await searchPredict.CountAsync();                var items = await searchPredict.ToPageListAsync(queryDto.PageIndex, queryDto.PageSize);                if (items == null) return new PageDataList<OrganizationDto>();                var orgs = items.Adapt<List<OrganizationDto>>();                var pagedData = new PageDataList<OrganizationDto>(totalCount, orgs, queryDto.PageIndex, queryDto.PageSize);                return pagedData;            }            else            {                var searchPredict = _unitOfWork.QueryClient.Queryable<OrganizationEntity>()                .Where(x => x.IsDeleted == 0 && x.RootId == queryDto.CurrentOrgId)                .WhereIF(queryDto.OrgIds.Any(), x => !queryDto.OrgIds.Contains(x.Id)) //---过滤分社                //.WhereIF(queryDto.CityId > 0, x => x.CityId == queryDto.CityId)                //.WhereIF(queryDto.ProvinceId > 0, x => x.ProvinceId == queryDto.ProvinceId)                .OrderBy(x => x.OrgLevel).OrderBy(x => x.Id);
                //大社获取分社加门店
                var dtoList = new List<OrganizationDto>();                var totalCount = await searchPredict.CountAsync();                if (await searchPredict.ToListAsync() == null) return new PageDataList<OrganizationDto>();                foreach (var orgEntity in await searchPredict.ToListAsync())                {                    if (orgEntity.OrgLevel == (int)OrgLevel.Branch)                    {
                        //var children = await GetSubOrgLists(orgEntity.Id, queryDto.KeyWords);
                        var children = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Where(x => x.ParentId == orgEntity.Id).ToListAsync();
                        var orgInfoDto = new OrganizationDto()
                        {
                            Id = orgEntity.Id,
                            Name = orgEntity.Name,
                            ShortName = orgEntity.ShortName,
                            OrgLevel = orgEntity.OrgLevel,
                            CityName = orgEntity.CityName,
                            CityId = orgEntity.CityId,
                            DistrictName = orgEntity.DistrictName,
                            ProvinceName = orgEntity.ProvinceName,
                            ProvinceId = orgEntity.ProvinceId,
                            TownName = orgEntity.TownName,
                            Address = orgEntity.Address,
                            IsDisabled = orgEntity.IsDisabled,
                            IsFrozen = orgEntity.IsFrozen,
                            LevelPath = orgEntity.LevelPath,
                            IsAllowOpenStores = orgEntity.IsAllowOpenStores,
                            children = GetChildren(orgEntity, children),
                            LeaderPhone = orgEntity.LeaderPhone,
                            LeaderName = orgEntity.LeaderName
                        };
                        if (orgEntity.ParentId <= 0)
                        {
                            orgInfoDto.ParentOrgName = "--";
                            orgInfoDto.ParentOrgLevel = -1;
                        }
                        else
                        {
                            var parentOrgInfo = await _repository.GetOrganizationInfoById(orgEntity.ParentId);
                            orgInfoDto.ParentOrgName = parentOrgInfo.Name;
                            orgInfoDto.ParentOrgLevel = parentOrgInfo.OrgLevel;
                            orgInfoDto.ParentId = parentOrgInfo.Id;
                            orgInfoDto.ParentIsAllowOpenStores = parentOrgInfo.IsAllowOpenStores;
                        }

                        dtoList.Add(orgInfoDto);
                    }                    else if ((orgEntity.OrgLevel == (int)OrgLevel.Store || orgEntity.OrgLevel == (int)OrgLevel.DirectlyUnder) && orgEntity.ParentId == queryDto.CurrentOrgId)
                    {                        var orgInfoDto = orgEntity.Adapt<OrganizationDto>();                        dtoList.Add(orgInfoDto);                    }                }                var resList = new List<OrganizationDto>();                dtoList.ForEach(one =>                {                    if ((!string.IsNullOrEmpty(queryDto.LeaderName) ? one.LeaderName.Contains(queryDto.LeaderName) : true) && (!string.IsNullOrEmpty(queryDto.KeyWords) ? one.Name.Contains(queryDto.KeyWords) : true) && ((queryDto.ProvinceId == 0 && queryDto.CityId == 0) ? true : (one.ProvinceId == queryDto.ProvinceId && one.CityId == queryDto.CityId)))                    {                        resList.Add(one);                    }                    else                    {                        if (one.children != null && one.children.Count > 0)                        {                            one.children.ForEach(two =>                            {                                if ((!string.IsNullOrEmpty(queryDto.LeaderName) ? one.LeaderName.Contains(queryDto.LeaderName) : true) && (!string.IsNullOrEmpty(queryDto.KeyWords) ? two.Name.Contains(queryDto.KeyWords) : true) && ((queryDto.ProvinceId == 0 && queryDto.CityId == 0) ? true : (two.ProvinceId == queryDto.ProvinceId && two.CityId == queryDto.CityId)))                                {                                    if (resList.Find(x => x.Id == one.Id) == null)                                    {                                        resList.Add(one);                                        one.children = new List<OrganizationDto>();                                    }                                    if (one.children.Find(x => x.Id == two.Id) == null)                                    {                                        one.children.Add(two);                                    }                                }                                else                                {                                    if (two.children != null && two.children.Count > 0)                                    {                                        two.children.ForEach(three =>                                        {                                            if ((!string.IsNullOrEmpty(queryDto.LeaderName) ? one.LeaderName.Contains(queryDto.LeaderName) : true) && (!string.IsNullOrEmpty(queryDto.KeyWords) ? three.Name.Contains(queryDto.KeyWords) : true) && ((queryDto.ProvinceId == 0 && queryDto.CityId == 0) ? true : (three.ProvinceId == queryDto.ProvinceId && three.CityId == queryDto.CityId)))                                            {                                                if (resList.Find(x => x.Id == one.Id) == null)                                                {                                                    resList.Add(one);                                                    one.children = new List<OrganizationDto>();                                                }                                                if (one.children.Find(x => x.Id == two.Id) == null)                                                {                                                    one.children.Add(two);                                                    two.children = new List<OrganizationDto>();                                                }                                                if (two.children.Find(x => x.Id == three.Id) == null)                                                {                                                    two.children.Add(three);                                                }                                            }                                        });                                    }                                }                            });                        }                    }                });

                var pageList = resList.Skip((queryDto.PageIndex - 1) * queryDto.PageSize).Take(queryDto.PageSize).ToList();

                return new PageDataList<OrganizationDto>(resList.Count, pageList, queryDto.PageIndex, queryDto.PageSize);            }        }

        private async Task<List<OrganizationEntity>> GetSubOrgLists(int orgId, string keywords)
        {
            var subOrgEntityList = await _repository.GetSubOrganizations(orgId, keywords);
            return subOrgEntityList;
        }

        /// <summary>
        /// 分社和门店
        /// 签约大社/分社下未直接签约的分社和门店
        /// </summary>
        /// <param name="lst">已经签约的大社/分社</param>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrganizationDto>> GetInheritSignOrgPageData(List<OrgSimpleDto> allSignedOrg, List<OrgSimpleDto> signedOrg, List<OrgSupplierReleaseSettingsView> allSettings, OrganizationQueryDto queryDto)
        {
            var exist = signedOrg.Select(o => o.Id).ToList();
            var all = allSignedOrg.Select(o => o.Id).ToList();
            var set = allSettings.Select(x => x.OrgId).ToList();
            List<int> setOrgList = new List<int>();

            //设置了范围
            if (allSettings.Count > 0)
            {
                var orgIds = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Where(x => exist.Contains(x.RootId) || exist.Contains(x.ParentId) || exist.Contains(x.Id)).ToListAsync();//全部签约关系下的组织机构
                var settings = allSettings.Select(x => x.MasterOrgId).ToList().Distinct().ToList();//设置了范围的机构
                var unSettgins = exist.Except(settings).ToList();//找出没有设置范围的签约机构
                setOrgList.AddRange(allSettings.Select(x => x.OrgId).ToList());
                foreach (var item in unSettgins)
                {
                    var org = orgIds.Where(x => x.Id == item).FirstOrDefault();
                    if (org.OrgLevel == (int)OrgLevel.Master)
                    {
                        //过滤大社下单独设置范围的分社
                        //大社下全部独立分社
                        var allowBrach = orgIds.Where(x => x.OrgLevel == (int)OrgLevel.Branch && x.RootId == item
                        && x.IsAllowContractSupplier == (short)AllowContractSupplier.Yes).ToList().Select(x => x.Id).ToList();
                        //全部分社
                        var setOrgs = allSettings.Where(x => x.MasterOrgLevel == (int)OrgLevel.Branch).Select(x => x.MasterOrgId).ToList();
                        var unOrgs = allowBrach.Intersect(setOrgs).ToList();
                        //需要过滤分社，因为分社单独设置了范围
                        if (unOrgs.Count > 0)
                        {
                            var unOrg = orgIds.Where(x => x.RootId == item && !unOrgs.Contains(x.ParentId) && !unOrgs.Contains(x.Id)).ToList();//需要排除的分社数据
                            if (unOrg.Count > 0)
                            {
                                var res = unOrg.Select(x => x.Id).ToList();
                                setOrgList.AddRange(res);
                            }
                        }
                        else
                        {
                            //如果不需要过滤，则直接获取全部
                            var res = orgIds.Where(x => x.RootId == item).ToList().Select(x => x.Id).ToList();
                            setOrgList.AddRange(res);
                        }
                    }
                    else if (org.OrgLevel == (int)OrgLevel.Branch)
                    {
                        var res = orgIds.Where(x => x.ParentId == item).ToList().Select(x => x.Id).ToList();
                        setOrgList.AddRange(res);
                    }
                }
            }

            //过滤出存在分社签约但是检索结果中不存在的分社
            var exceptBranch = allSignedOrg.FindAll(o => o.OrgLevel == (int)OrgLevel.Branch).Select(o => o.Id).Except(exist);
            var levels = new List<int>();
            if (queryDto.OrgLevel == (int)OrgLevel.Branch)
            {
                levels.Add((int)OrgLevel.Branch);
            }
            else if (queryDto.OrgLevel == (int)OrgLevel.Store)
            {
                levels.Add((int)OrgLevel.DirectlyUnder);
                levels.Add((int)OrgLevel.Store);
            }
            var searchPredict = _unitOfWork.QueryClient.Queryable<OrganizationEntity, OrganizationEntity>((o1, o2) => new object[] {
                JoinType.Inner,o1.Id==o2.ParentId})
               .Where((o1, o2) => o2.IsDeleted == 0)
               .Where((o1, o2) => levels.Contains(o2.OrgLevel))
               .WhereIF(queryDto.OrgLevel == (int)OrgLevel.Branch, (o1, o2) => exist.Contains(o2.ParentId) && !exist.Contains(o2.Id))//分社取没有签约
               .WhereIF(queryDto.OrgLevel == (int)OrgLevel.Store, (o1, o2) => exist.Contains(o2.RootId) || exist.Contains(o2.ParentId))//取当前总社下所有门店
               .WhereIF(queryDto.OrgLevel == (int)OrgLevel.Store && exceptBranch.Any(), (o1, o2) => !exceptBranch.Contains(o2.ParentId))
               .WhereIF(queryDto.OrgLevel == (int)OrgLevel.Branch && set.Count > 0, (o1, o2) => set.Contains(o2.Id))
               .WhereIF(queryDto.OrgLevel == (int)OrgLevel.Store && setOrgList.Count > 0, (o1, o2) => setOrgList.Contains(o2.Id))
               .WhereIF(!string.IsNullOrEmpty(queryDto.Keywords), (o1, o2) => o2.Name.Contains(queryDto.Keywords))
               .WhereIF(!string.IsNullOrEmpty(queryDto.ParentOrgName), (o1, o2) => o1.Name.Contains(queryDto.ParentOrgName))
               .OrderBy((o1, o2) => o2.ParentId, OrderByType.Asc)
               .OrderBy((o1, o2) => o2.Id, OrderByType.Asc)
               .OrderBy((o1, o2) => o2.Name, OrderByType.Asc)
               .GroupBy((o1, o2) => new { o2.Id, o2.Name, ParentId = o1.Id, ParentOrgName = o1.Name, o1.LevelPath })
               .Select((o1, o2) => new OrganizationDto()
               {
                   Id = o2.Id,
                   Name = o2.Name,
                   ParentId = o1.Id,
                   ParentOrgName = o1.Name,
                   LevelPath = o1.LevelPath,
               });
            var totalCount = await searchPredict.CountAsync();
            var entities = await searchPredict.ToPageListAsync(queryDto.PageIndex, queryDto.PageSize);
            var orgPageList = new PageDataList<OrganizationDto>(totalCount, entities, queryDto.PageIndex, queryDto.PageSize);
            return orgPageList;
        }

        /// <summary>
        /// 获取指定组织机构下所有子集
        /// </summary>
        /// <param name="orgIds"></param>
        /// <returns></returns>
        public async Task<List<SignProductOrg>> GetOrgSimpleByIds(List<string> orgIds)
        {
            if (orgIds.Any())
            {
                string orgidList = string.Empty;
                foreach (var org in orgIds)
                {
                    if (orgidList == string.Empty)
                    {
                        orgidList += $"^{org}";
                    }
                    else
                    {
                        orgidList += $"|^{org}";
                    }
                }
                var sql = $@"SELECT * FROM admin_user.organization  WHERE IsDeleted =0 and LevelPath REGEXP '{orgidList}' ORDER BY LevelPath";
                var list = await _unitOfWork.QueryClient.SqlQueryable<OrganizationEntity>(sql)
                    .Select(x => new SignProductOrg()
                    {
                        OrgId = x.Id,
                        OrgName = x.Name,
                        OrgLevel = x.OrgLevel,
                        OrgLevelPath = x.LevelPath,
                        ParentOrgId = x.ParentId
                    })
                    .ToListAsync();
                return list;
            }
            return new List<SignProductOrg>();
        }

        /// <summary>
        /// 根据Id集合获取组织机构信息
        /// </summary>
        /// <param name="orgIds"></param>
        /// <returns></returns>
        public async Task<List<OrganizationEntity>> GetOrganizationEntityByOrgIdList(List<int> orgIds)
        {
            if (orgIds.Count > 0)
            {
                var res = await _unitOfWork.QueryClient.Queryable<OrganizationEntity>().Where(x => orgIds.Contains(x.Id)).ToListAsync();
                return res;
            }
            return new List<OrganizationEntity>();
        }
    }
}
